package org.example.redis;

import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;

import java.util.concurrent.atomic.AtomicInteger;

public class RateLimiter {
    public static void main(String[] args) throws InterruptedException {
        RedissonClient redisson = RedissonUtil.getRedisson();
        RRateLimiter rateLimiter = redisson.getRateLimiter("goods:num");

        final AtomicInteger success = new AtomicInteger(0);
        final AtomicInteger fail = new AtomicInteger(0);

        // 限流初始化
        // 每1秒产生一个令牌
        rateLimiter.trySetRate(RateType.OVERALL, 1, 1, RateIntervalUnit.SECONDS);

        for (int i = 0; i < 100; i++) {
            if (rateLimiter.tryAcquire(1)) {
                success.incrementAndGet();
                Thread.sleep(100);
            } else {
                fail.incrementAndGet();
            }
        }
        System.out.println("成功令牌数：" + success + ", 失败令牌数：" + fail);
    }
}
